package com.zty.xiaomi.server.utils;

import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author Losca
 * @date 2022/2/21 19:21
 */
@Component
public class FileUtil {
    @Value("${minio.url}")
    private String minioUrl;
    @Value("${minio.username}")
    private String minioUsername;
    @Value("${minio.password}")
    private String minioPassword;

    public String uploadToMinio(MultipartFile file, String bucket) throws Exception{
        StringBuilder builder = new StringBuilder(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")));
        // 拼接随机数
        builder.append(RandomStringUtils.random(6,false,true));
        // 拼接后缀
        builder.append(".").append(FilenameUtils.getExtension(file.getOriginalFilename()));
        MinioClient minioClient = new MinioClient(minioUrl, minioUsername, minioPassword);
        //图片是否分块
        PutObjectOptions options = new PutObjectOptions(file.getSize(),0);
        //设置文件格式，图片能够被在线预览
        options.setContentType(file.getContentType());
        // 使用putObject上传一个文件到存储桶中。
        minioClient.putObject("img",builder.toString(),file.getInputStream(),options);
        //返回图片地址
        return bucket + "/" + builder.toString();
    }
}
